package com.authine.cloudpivot.web.api.secondopen.controller;

import com.authine.cloudpivot.web.api.controller.base.BaseController;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * @Author: brookpeng
 * @Date: 2021/8/30 18:13
 */
@Api(value = "二开接口", tags = "单点登录生成token")
@RestController
@RequestMapping("/api/ossTokenProvider")
public class OssTokenProviderController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(OssTokenProviderController.class);

    private static final String SECRET_KEY = "HxSecretKey184308302021#!";

    private static final long validity = 1000 * 60 * 60 * 24;

    /**
     * 颁发Token
     * @return
     */
    @GetMapping("/getToken")
    public String getToken() {
        String userId = getUserId();
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowTime = System.currentTimeMillis();
        Date nowDate = new Date(nowTime);
        byte[] keyBytes = DatatypeConverter.parseBase64Binary(SECRET_KEY);
        String jacName = signatureAlgorithm.getJcaName();
        Key secretKeySpec = new SecretKeySpec(keyBytes, jacName);
        JwtBuilder jwtBuilder = Jwts.builder()
                .claim("userId", userId)
                .setIssuedAt(nowDate)
                .signWith(signatureAlgorithm, secretKeySpec);
        long expMillis = nowTime + validity;
        Date exp = new Date(expMillis);
        jwtBuilder.setExpiration(exp);
        return jwtBuilder.compact();
    }
}
